<?php
/**
 * Created by PhpStorm.
 * User: ycbwl
 * Date: 2018/11/9
 * Time: 11:21 PM
 */
namespace app\api\service;

use app\api\model\Address;
use app\api\model\OrderProduct;
use app\api\model\Product;
use app\api\validate\PagingParameter;
use app\lib\exception\OrderException;
use app\lib\exception\UserException;
use app\api\model\Order as OrderModel;
use think\Db;
use think\Exception;

class Order{

    //订单的商品列表，也就是客户端products参数
    protected $oProducts;

    //真是的商品信息（包括库存量）
    protected $products;

    protected $uid;

    /**
     * @param int $page
     * @param int $size
     * 获取用户订单列表
     */
    public function getOrdersByUser($page = 1,$size = 10){
        (new PagingParameter())->goCheck();
        $uid = \app\lib\Token::getDataForToken('id','mini');
        $order = OrderModel::getOrderByUser($uid,$page,$size);
        return $order;
    }


    public function place($uid,$oProducts){
        //oProduct和products对比  作对比
        //products从数据库查询出来
        $this->oProducts = $oProducts;
        foreach ($this->oProducts as &$v){
            $v['count'] = $v['counts'];
        }
        $this->products = $this->getProductsByOrder($oProducts);
        $this->uid = $uid;
        $status = $this->getOrderStatus();
        if(!$status['pass']){
            $status['order_id'] = -1;
            return $status;
        }
        //开始创建订单
        $orderSnap = $this->snapOrder($status);
        $order = $this->createOrder($orderSnap);
        $order['pass'] = true;
        return $order;
    }


    private function createOrder($snap){
        try{
            Db::startTrans();
            $orderNo = self::makeOrderNo();
            $order = new OrderModel();
            $order->user_id = $this->uid;
            $order->order_no = $orderNo;
            $order->total_price = $snap['orderPrice'];
            $order->total_count = $snap['totalCount'];
            $order->snap_img = $snap['snapImg'];
            $order->snap_name = $snap['snapName'];
            $order->snap_address = $snap['snapAddress'];
            $order->snap_items = json_encode($snap['pStatus']);
            $order->status = 2;
            $order->save();
            $orderID = $order->id;
//            $createTime = $order->create_time;
            foreach ($this->oProducts as &$p){
                $p['order_id'] = $orderID;
            }
            $orderProduct = new OrderProduct();
            $orderProduct->saveAll($this->oProducts);
            Db::commit();
            return [
                'order_no'=>$orderNo,
                'order_id'=>$orderID,
                'create_time'=>time()
            ];
        }catch (Exception $exception){
            Db::rollback();
            throw $exception;
        }


    }

    public static function makeOrderNo()
    {
        $yCode = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J');
        $orderSn =
            $yCode[intval(date('Y')) - 2017] . strtoupper(dechex(date('m'))) . date(
                'd') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf(
                '%02d', rand(0, 99));
        return $orderSn;
    }



    //生成订单快照
    private function snapOrder($status){
        $snap = [
            'orderPrice' => 0,
            'totalCount' => 0,
            'pStatus' => [],
            'snapAddress' => '',
            'snapName' => '',
            'snapImg' => ''
        ];
        $snap['orderPrice'] = $status['orderPrice'];
        $snap['totalCount'] = $status['totalCount'];
        $snap['pStatus'] = $status['pStatusArray'];
        $snap['snapAddress'] = json_encode( $this->getUserAddress());
        $snap['snapName'] = $this->products[0]['name'];
        $snap['snapImg'] = $this->products[0]['main_img_url'];
        if(count($this->products) > 1){
            $snap['snapName'] .= '等';
        }
        return $snap;
    }

    private function getUserAddress(){
        $userAddress = Address::where('user_id',$this->uid)->find();
        if(!$userAddress){
            throw new UserException([
                'msg'=>'用户收获地址不存在，下单失败',
                'errorCode'=>60001
            ]);
        }
        return $userAddress->toArray();
    }


    public function checkOrderStock($orderID){
        $oProducts = OrderProduct::where("order_id",$orderID)->select();
        $this->oProducts = $oProducts;
        foreach ($this->oProducts as &$v){
            $v['counts'] = $v['count'];
        }
        $this->products = $this->getProductsByOrder($oProducts);
        $status = $this->getOrderStatus();
        return $status;
    }


    private function getOrderStatus(){
        $status = [
            'pass'=>true,
            'orderPrice'=>0,
            'totalCount'=>0,
            'pStatusArray'=>[]
        ];
        foreach ($this->oProducts as $oProduct){
            $pStatus = $this->getProductStatus($oProduct['product_id'],$oProduct['counts'],$this->products);
            if(!$pStatus['haveStock']){
                $status['pass'] = false;
            }
            $status['orderPrice'] += $pStatus['totalPrice'];
            $status['totalCount'] += $pStatus['count'];
            array_push($status['pStatusArray'],$pStatus);
        }
        return $status;
    }


    private function getProductStatus($oPID,$oCount,$products){
        $pIndex = 0;
        $pStatus = [
            'id'=>null,
            'haveStock'=>false,
            'count'=>0,
            'name'=>'',
            'totalPrice'=>0
        ];
        for($i=0;$i<count($products);$i++){
            if($oPID == $products[$i]['id']){
                $pIndex = $i;
            }
        }
        if($pIndex == -1){ //客户端传的商品不存在   抛出异常
            throw new OrderException([
                'msg'=>'id为'.$oPID.'的商品不存在，创建订单失败'
            ]);
        }else{
            $product = $products[$pIndex];
            $pStatus['id'] = $product['id'];
            $pStatus['name'] = $product['name'];
            $pStatus['count'] = $oCount;
            $pStatus['totalPrice'] = $product['price'] * $oCount;
            if($product['stock'] - $oCount >= 0){
                $pStatus['haveStock'] = true;
            }
        }
        return $pStatus;

    }



    //根据订单信息查找真实的商品信息
    private function getProductsByOrder($oProducts){
//        foreach ($oProducts as $k=>$v){
//            //循环的查询数据库
//        }
        $oPIDs = [];
        foreach ($oProducts as $v){
            array_push($oPIDs,$v['product_id']);
        }
        $products = Product::all($oPIDs)->visible(['id','price','stock','name','main_img_url']);
        return $products;
    }


}